/** 
 * Revisions JS handler
 */
 
function Revisions() {
  this.revs = [];
  this.selectedRev = 0;
  this.lastPath = null;
  
  this.initialize = function() {
    var r = this;
    this.loadCommits();
  
    //$("#rev_date").datepicker();
    
    // Revisions slider
    $("#rev_slider")
      .slider({"min": 1, "max": 100, "step": 1, "value": 100})
      .bind("slide", function(e, ui) { r.slideChange.call(r, e, ui) })
      .bind("slidestop", function(e, ui) { r.slideStop.call(r, e, ui) });
    
    // Load file tree
    gsp.scheduleTask(this.loadFileBrowser, this);
  };
  
  // Create treeview file browser
  this.loadFileBrowser = function() {
    var r = this;
     
    $("#rev_file_tree").fileTree({
      root: '/',
      script: function() {
        return r.getPathRequest.call(r);
      },
      expandSpeed: 500,
      collapseSpeed: 500,
      multiFolder: true
    },
      // Click on file handler
      function(file) { r.openFile.call(r, file); }
    );
  };
  
  // Open file at path in given revision
  this.openFile = function(file) {
    var project = gsp.getSelectedProject();
    var params = {"name": project, "sha": this.selectedRev[0], "path": file};
    this.lastPath = file;
    
    gsp.request("browse_revision", params,
      // File handler
      function(dt) {
        // Replace tabulators with 2 spaces
        dt = dt.replace(/\t/g, '&nbsp;&nbsp');
        $("#rev_file_content").html(dt);
      },
      
      // Error handler
      function(err) { return true;}
    );
  }
  
  // Return parameters to open clicked path
  this.getPathRequest = function() {
    var project = gsp.getSelectedProject();
    
    return {
      url: "browse_revision",
      name: project,  
      sha: this.selectedRev[0]
    };
  };
  
  // Load last 100 commits
  this.loadCommits = function() {
    var project = gsp.getSelectedProject();
    var r = this;
    
    gsp.request("revisions", {name: project}, function(dt) {
      r.revs = dt;
      r.selectedRev = dt[0];
      r.setDate(dt[0][1]);
      r.setShaMessage(dt[0][0]);
      
      $("#rev_slider").slider("option", {"max": dt.length, "value": dt.length});
    });
  };
  
  // Update sha number in content view
  this.setShaMessage = function(sha) {
    var msg = '<div id="rev_sha">'+ sha +'</div>';
    $("#rev_file_content").html(msg);
  };
  
  // Slider sliding
  this.slideChange = function(e, ui) {
    var idx = this.revs.length - ui.value;
    this.setDate(this.revs[idx][1]);
    this.setShaMessage(this.revs[idx][0]);
  };
  
  // Slider stop sliding
  this.slideStop = function(e, ui) {
    var idx = this.revs.length - ui.value;
    this.selectedRev = this.revs[idx];
    this.loadFileBrowser();
    
    if (this.lastPath)
      this.openFile(this.lastPath);
  };
  
  // Set revision date
  this.setDate = function(tstamp) {
    $("#rev_date").val(gsp.date(tstamp));
  };
}


var loader = function(){ (new Revisions()).initialize(); };
